package red.yancloud.www.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import com.alibaba.fastjson.JSONObject
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.google.gson.Gson
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_personal_information.*
import okhttp3.ResponseBody
import org.json.JSONArray
import red.yancloud.www.R
import red.yancloud.www.base.BaseActivity
import red.yancloud.www.common.Constants
import red.yancloud.www.db.sharedpreference.UserInfoShardPreference
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.City
import red.yancloud.www.internet.bean.Default
import red.yancloud.www.internet.bean.Login
import red.yancloud.www.util.AppUtils
import red.yancloud.www.util.ToastUtils


/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/6/12 14:48
 * E_Mail：yh131412hys@163.com
 * Describe：个人资料
 * Change：
 * @Version：V1.0
 */
class PersonalInformationActivity : BaseActivity(), View.OnClickListener {

    private val TAG = "onalInformationActivity"

    private val MSG_LOAD_DATA = 0x0001
    private val MSG_LOAD_SUCCESS = 0x0002
    private val MSG_LOAD_FAILED = 0x0003
    private var thread: Thread? = null
    private var isLoaded = false
    private var options1Items: List<City> = ArrayList()
    private val options2Items = ArrayList<ArrayList<String>>()
    private val options3Items = ArrayList<ArrayList<ArrayList<String>>>()
    private var isModifyUserInfo = false
    private var lastUserName:String =""
    private var lastName:String =""
    private var lastAddress:String =""
    private var lastPartyBranch:String =""
    private var opt1tx:String=""
    private var opt2tx:String=""
    private var opt3tx:String=""


    @SuppressLint("HandlerLeak")
    private val mHandler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                MSG_LOAD_DATA -> if (thread == null) {//如果已创建就不再重新创建子线程了

                    thread = Thread(Runnable {
                        // 子线程中解析省市区数据
                        initJsonData()
                    })
                    thread!!.start()
                }

                MSG_LOAD_SUCCESS ->

                    isLoaded = true

                MSG_LOAD_FAILED ->

                    ToastUtils.showToast("地址数据解析异常")
            }
        }
    }

    override val layoutId: Int
        get() = R.layout.activity_personal_information

    override fun initData() {

        mHandler.sendEmptyMessage(MSG_LOAD_DATA)
        getUserInfo()
    }

    private fun getUserInfo() {

        loadingDialog.show()

        RedCloudApis.getInstance().userInfo(UserInfoShardPreference.instance.uid, object : Observer<ResponseBody> {
            override fun onComplete() {
            }

            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: ResponseBody) {

//                在实际开发中，响应主体 RessponseBody 持有的资源可能会很大，所以 OkHttp 并不会将其直接保存到内存中，只是持有数据流连接。只有当我们需要时，才会从服务器获取数据并返回。同时，考虑到应用重复读取数据的可能性很小，所以将其设计为一次性流(one-shot)，读取后即 ‘关闭并释放资源’。
                val result = String(t.bytes())
                val jsonObject = JSONObject.parseObject(result)
                Log.d(TAG, "====jsonObject:$jsonObject")
                val code = jsonObject.getString("code")

                if (code == Constants.SYSTEM_OK) {

                    val loginEntity = JSONObject.parseObject(result, Login::class.java)

                    val data = loginEntity.data
                    lastUserName = data.username
                    personalInformationActivity_userName_et.setText(lastUserName)
                    personalInformationActivity_userName_et.setSelection(lastUserName.length)
//                    java.lang.IllegalStateException: data.name must not be null
                    /*{"code":"0000","data":{"id":"223","username":"yh1314","pwd":"a5f06a7338dc927e7a4c8845d8f1c07a","remark":null,"sex":"0","mobile":null,"email":"1328060337@qq.com","province":null,"city":null,"area":null,"headimgurl":null,"redstarcoin":"100","organization":null,"addtime":"2019-07-31 16:46:01","lasttime":null,"userstatus":"1","emailstatus":"0","openid":null,"third_login_type":null,"subscribe":"1","subscribe_time":null,"name":null,"rmb":"0.00","fee_type":"0","start_time":null,"end_time":null},"msg":"success"}*/
                    if (!TextUtils.isEmpty(data.name)) {

                        lastName = data.name
                        personalInformationActivity_name_et.setText(lastName)
                        personalInformationActivity_name_et.setSelection(lastName.length)
                    }
                    if (!TextUtils.isEmpty(data.province)&&!TextUtils.isEmpty(data.city)&&!TextUtils.isEmpty(data.area)) {

                        lastAddress = "${data.province}-${data.city}-${data.area}"
                        personalInformationActivity_addressInfo_tv.text = lastAddress
                    }
                    if (!TextUtils.isEmpty(data.organization)) {

                        lastPartyBranch = data.organization
                        personalInformationActivity_partyBranch_et.setText(lastPartyBranch)
                        personalInformationActivity_partyBranch_et.setSelection(lastPartyBranch.length)
                    }
                } else {

                    ToastUtils.showToast(jsonObject.getString("msg"))
                }

                loadingDialog.dismiss()
            }

            override fun onError(e: Throwable) {

                loadingDialog.dismiss()
            }
        })
    }

    override fun configViews() {

        back_iv.setOnClickListener(this)
        save_tv.setOnClickListener(this)
        personalInformationActivity_addressInfo_rl.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.back_iv-> finish()
            R.id.save_tv -> {

                val userName = personalInformationActivity_userName_et.text.toString().trim()
                if (userName.isEmpty()) {

                    ToastUtils.showToast("请输入用户名")
                    return
                }
                if (userName!=lastUserName) {

                    isModifyUserInfo=true
                }

                val name = personalInformationActivity_name_et.text.toString().trim()
                if (name.isEmpty()) {

                    ToastUtils.showToast("请输入姓名")
                    return
                }
                if (name!=lastName) {

                    isModifyUserInfo=true
                }

                val address = personalInformationActivity_addressInfo_tv.text.toString().trim()
                if (address.isEmpty()) {

                    ToastUtils.showToast("请选择地址")
                    return
                }
                if (address!=lastAddress) {

                    isModifyUserInfo=true
                }

                val partyBranch = personalInformationActivity_partyBranch_et.text.toString().trim()
                if (partyBranch.isEmpty()) {

                    ToastUtils.showToast("请输入用户名")
                    return
                }
                if (partyBranch!=lastPartyBranch) {

                    isModifyUserInfo=true
                }

                if (isModifyUserInfo) {
                    RedCloudApis.getInstance().editUser(UserInfoShardPreference.instance.uid,name,opt1tx,opt2tx,opt3tx,partyBranch,object :
                        Observer<Login> {
                        override fun onComplete() {
                        }

                        override fun onSubscribe(d: Disposable) {
                        }

                        override fun onNext(t: Login) {

                            Log.d(TAG,t.toString())
                            if (t.code == Constants.SYSTEM_OK) {

                                UserInfoShardPreference.instance.saveUserInfo(t.data)
                                ToastUtils.showToast("用户信息修改成功")
                                finish()
                            }else{

                                ToastUtils.showToast("用户信息修改失败")
                            }
                        }

                        override fun onError(e: Throwable) {
                        }
                    })
                }else{

                    ToastUtils.showToast("请修改用户信息后提交保存")
                }
            }
            R.id.personalInformationActivity_addressInfo_rl -> {
                if (isLoaded) {

                    /**隐藏软键盘**/
                    val view = window.peekDecorView()
                    if (view != null) {
                        val inputmanger = mContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                        inputmanger.hideSoftInputFromWindow(view.windowToken, 0)
                    }

                    showPickerView()
                } else {
                    ToastUtils.showToast("城市数据解析中，请稍后...")
                }
            }
        }
    }

    private fun showPickerView() {// 弹出选择器

        val pvOptions = OptionsPickerBuilder(this,
            OnOptionsSelectListener { options1, options2, options3, _ ->
                //返回的分别是三个级别的选中位置
                opt1tx = if (options1Items.size > 0)
                    options1Items[options1].pickerViewText
                else
                    ""

                opt2tx = if (options2Items.size > 0 && options2Items[options1].size > 0)
                    options2Items[options1][options2]
                else
                    ""

                opt3tx = if (options2Items.size > 0
                    && options3Items[options1].size > 0
                    && options3Items[options1][options2].size > 0)
                    options3Items[options1][options2][options3]
                else
                    ""

                /*String tx = opt1tx + opt2tx + opt3tx;*/
                personalInformationActivity_addressInfo_tv.text = "$opt1tx-$opt2tx-$opt3tx"
            })
            //                .setLabels(province,city,district)
            .setTitleText("城市选择")
            .setDividerColor(Color.BLACK)
            .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
            .setContentTextSize(20)
            .build<Any>()

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items as List<ArrayList<String>>,
            options3Items as List<ArrayList<ArrayList<String>>>
        )//三级选择器
        pvOptions.show()
    }

    private fun initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * 获取assets目录下的json文件数据
         */
        val JsonData = AppUtils.getJson(this, "province.json")

        val jsonBean = parseData(JsonData)//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean

        for (i in jsonBean.indices) {//遍历省份
            val cityList = ArrayList<String>()//该省的城市列表（第二级）
            val province_AreaList = ArrayList<ArrayList<String>>()//该省的所有地区列表（第三极）

            for (c in 0 until jsonBean[i].cityList.size) {//遍历该省份的所有城市
                val cityName = jsonBean[i].cityList[c].name
                cityList.add(cityName)//添加城市
                val city_AreaList = ArrayList<String>()//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                /*if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    city_AreaList.add("");
                } else {
                    city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }*/
                city_AreaList.addAll(jsonBean[i].cityList.get(c).area)
                province_AreaList.add(city_AreaList)//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList)

            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList)
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS)

    }

    private fun parseData(result: String): ArrayList<City> {//Gson 解析

//        val cityBean = City.CityBean()
//        cityBean.setName(city)
//        val area = ArrayList<String>()
//        area.add(district)
//        cityBean.setArea(area)
//
//        val provinceBean = City()
//        provinceBean.setName(province)
//        val city = ArrayList<City.CityBean>()
//        city.add(cityBean)
//        provinceBean.setCityList(city)

        val detail = ArrayList<City>()
//        detail.add(provinceBean)
        try {
            val data = JSONArray(result)
            val gson = Gson()
            for (i in 0 until data.length()) {
                val entity = gson.fromJson(data.optJSONObject(i).toString(), City::class.java)
                detail.add(entity)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED)
        }

        return detail
    }
}
